package com.batchengine.worker;

import static com.batchengine.Definitions.ContextParams.TASK_INSTANCE;
import com.batchengine.task.Task;
import com.batchengine.task.TaskContext;
import static com.batchengine.task.TaskUtil.getTaskContext;
import static com.batchengine.util.LoggingFactory.createLogger;
import static com.batchengine.worker.Status.FINISHED;
import static com.batchengine.worker.Status.RUNNING;
import static com.batchengine.worker.WorkerType.EXECUTER;
import com.batchengine.Definitions;
import org.apache.log4j.Logger;

import static java.text.MessageFormat.format;

/**
 * Created by  solutions
 * Author: sunil.incubator@yahoo.com
 * Date: Aug 6, 2009
 * <p/>
 * This class will executes the configures task for only once
 */
public class TaskExecutor extends Executor {

    private static final Logger logger = createLogger();

    public TaskExecutor(String name, long taskId) {
        super(name, taskId);
    }

    protected TaskExecutor(String name, long taskId, ThreadGroup workGroup) {
        super(name, taskId, workGroup);
    }

    protected TaskExecutor(String name, long taskId, ThreadGroup workGroup, int workerPriority) {
        super(name, taskId, workGroup, workerPriority);
    }

    public final WorkerType getType() {
        return EXECUTER;
    }

    @Override
    public void run() {

        try {

            workerThread = Thread.currentThread();
            try {

                setStatus(RUNNING);
                doWork(getTaskContext(getJobId()));
            } catch (Exception ignored) {
                logger.error(format("error running the worker {0}", getName()),ignored);
                //do nothing - if stop is true then we will exit.
            }
        } finally {
            cleanUp(); // unnecessary but can help GC
            setStatus(FINISHED);
        }
    }

    protected void doWork(TaskContext context) {

        Task task = (Task) context.getContextParam(TASK_INSTANCE);
        context.addcontextParam(Definitions.ContextParams.OWNER, this);
        task.execute(context);
    }
}
